/*
 * main.cpp
 *
 *  Created on: Sep 20, 2015
 *      Author: rpi
 */

#include <iostream>
#include <thread>
#include <cstdio>
#include <cstdlib>
#include <csignal>

#include <json/json.h>
#include <jsonrpc.h>
#include <system.h>
#include <mysql.h>

#include "MySqlRpc.h"
#include "RpcService.h"

using namespace std;

RpcService<MySqlRpc> goRpcService("127.0.0.1", 8086);

/**
 * \brief Signal management.
 * \param code signal code
 */
static void signal_handler(int code)
{
  switch(code)
  {
    case SIGINT:
    case SIGTERM:
      //g_run = 0;
      break;
    default:
      break;
  }
}


static void initNetworking()
{
	if(!networking::init())
	{
	  std::cerr << "Networking initialization failed" << std::endl;
	  exit(EXIT_FAILURE);
	}
}

static void finaNetworking()
{
	networking::cleanup();
}

void initSignal()
{
	if(signal(SIGTERM, signal_handler) == SIG_ERR)
	{
		std::cout << "Error signal SIGTERM will not be handled" << std::endl;
	}

	if(signal(SIGINT, signal_handler) == SIG_ERR)
	{
		std::cout << "Error signal SIGINT will not be handled" << std::endl;
	}
}

int main(int argc, char **argv)
{
	/* avoid compilation warnings */
	(void)argc;
	(void)argv;

	initNetworking();
	initSignal();

	goRpcService.initialize();
	//RpcServer oDeviceRpcServer("127.0.0.1", 8086);

	while (1) system_util::msleep(1000);

	goRpcService.finalize();
	finaNetworking();

	return 0;
}
